package ms.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.exception.BizException;
import ms.db.mongodb.MongoReplicaSetRepository;
import org.apache.commons.collections.MapUtils;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/as/")
public class AutoScriptController extends BaseController {

    @Autowired
    MongoReplicaSetRepository mongoReplicaSetRepository;

    @RequestMapping(value = "/add")
    public Map addScript(@RequestBody Map param) {
        Map res = new HashMap();
        try {
            if (MapUtils.isEmpty(param)) {
                throw new BizException("required parameter not found!");
            }
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            DBObject item = new BasicDBObject();
            item.putAll(param);
            item.put("_id", id);
            DBObject data = mongoReplicaSetRepository.save(item);
            res.put("data", data);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("错误", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("错误", ex);
            this.failed(res, "严重错误");
        }
        return res;

    }

    @RequestMapping(value = "/get")
    public Map getScript(@RequestParam String sid) {
        Map res = new HashMap();
        try {
            Object data = mongoReplicaSetRepository.findById(sid);
            res.put("data", data);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("错误", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("错误", ex);
            this.failed(res, "严重错误");
        }
        return res;
    }
}
